package com.example.onlinetaxi.ui.activity.MainPage.OrderFragments;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.callback.OrderCallBack.CompletedOrderCallBack;
import com.example.onlinetaxi.callback.OrderCallBack.GetOrderCallBack;
import com.example.onlinetaxi.dto.OrderDto.CompletedOrderDto;
import com.example.onlinetaxi.ui.activity.CommentPage.CommentActivity;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.TimeUtil;
import com.example.onlinetaxi.util.alipayUtil.Config;
import com.example.onlinetaxi.util.alipayUtil.OrderInfoUtil2_0;
import com.example.onlinetaxi.util.alipayUtil.PayResult;
import com.example.onlinetaxi.view.Adapter.CompletedOrderAdapter;
import com.example.onlinetaxi.view.Dialog.MyDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CompleteOrderFragment extends Fragment {

    private View rootView;
    // 无订单提醒
    private TextView empty;
    // 订单列表
    private List<CompletedOrderDto> orderList = new ArrayList<>();
    // 选中的订单
    private CompletedOrderDto order;
    // 重新获取订单
    private GetOrderCallBack getOrderCallBack;
    // 请求参数
    private Map<String, String> map = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_complete_order, container, false);

        initView();

        initEvent();

        return rootView;
    }

    private void initView() {
        empty = rootView.findViewById(R.id.complete_order_empty);

        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        }
    }

    private void initEvent() {
        // 初始化订单列表控件
        initRecyclerView();

        // 初始化空页面
        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        } else {
            empty.setVisibility(View.VISIBLE);
        }
    }

    public void setOrderList(List<CompletedOrderDto> orderList) {
        this.orderList = orderList;
    }

    private void initRecyclerView() {
        // 找到布局文件中的recyclerView
        RecyclerView recyclerView = rootView.findViewById(R.id.complete_order_list);
        /*指定RecyclerView布局方式*/
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        /*指定为LinearLayout布局*/
        recyclerView.setLayoutManager(layoutManager);

        // 设置管理器颜色配置
        CompletedOrderAdapter.drawable7 = getContext().getDrawable(R.color.blue);
        CompletedOrderAdapter.drawable8 = getContext().getDrawable(R.color.perfect_green);
        CompletedOrderAdapter.drawable_pay_btn = getContext().getDrawable(R.drawable.blue_btn);
        CompletedOrderAdapter.drawable_delete_btn = getContext().getDrawable(R.drawable.exit_app_btn_bg);

        /*适配去管理滑动显示*/
        CompletedOrderAdapter adapter = new CompletedOrderAdapter(orderList);


        // 设置点击回调函数
        adapter.setCompletedOrderCallBack(new CompletedOrderCallBack() {
            @Override
            public void jump(CompletedOrderDto order) {
                // 点击后进行跳转,跳转到评价界面
                // 转换时间格式
                // 设置当前订单为选中订单
                LocalStorage.chosenOrder = TimeUtil.setRightTimeFormat(order);

                startActivity(new Intent(getActivity(), CommentActivity.class));
            }

            @Override
            public void clickPayButton(CompletedOrderDto order) {
                // 进行订单支付
                payV2(order);
            }

            @Override
            public void clickDeleteButton(CompletedOrderDto order) {
                // 弹出确认框
                showDialog(order);
            }
        });

        /*设置适配*/
        recyclerView.setAdapter(adapter);
    }

    private void showDialog(CompletedOrderDto order) {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 取消，不操作
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击确认
                // 删除订单
                deleteCompleteOrder(order);

                // 刷新当前页面
                refresh();

                Toast.makeText(getActivity(), "您已删除该订单!", Toast.LENGTH_SHORT).show();
            }
        };

        MyDialog.drawable = getContext().getDrawable(R.drawable.dialog_confirm_driver);

        // 显示提示框
        MyDialog.showInfoDialog(getActivity(), "您是否要删除当前订单记录？", "取消", onCancelClickListener, "确认", onConfirmClickListener);
    }

    private void deleteCompleteOrder(CompletedOrderDto order) {
        map.clear();

        map.put("orderId", String.valueOf(order.getCompleteOrderId()));

        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "completedOrder", "deleteOrder");
    }

    public void payV2(CompletedOrderDto order) {
        this.order = order;

        // 验证参数
        if (TextUtils.isEmpty(Config.APPID) || (TextUtils.isEmpty(Config.RSA2_PRIVATE) && TextUtils.isEmpty(Config.RSA_PRIVATE))) {
            showAlert(getActivity(), getString(R.string.error_missing_appid_rsa_private));
            return;
        }

        boolean rsa2 = (Config.RSA2_PRIVATE.length() > 0);
        // 创建订单信息
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(Config.APPID, rsa2, order.getCost());
        // 获取订单信息，用来打印
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? Config.RSA2_PRIVATE : Config.RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(getActivity());
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = Config.SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Config.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(getActivity(), "支付成功，订单完成!", Toast.LENGTH_SHORT).show();

                        // 向后端发送请求，表示用户支付成功
                        map.clear();

                        map.put("orderId", String.valueOf(order.getCompleteOrderId()));
                        map.put("pay", String.valueOf(order.getCost()));

                        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "completedOrder", "payOrder");

                        // 刷新页面
                        refresh();

                        // 清除当前订单信息
                        LocalStorage.currentOrder = null;
                        LocalStorage.currentOrderId = null;
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private static void showAlert(Context ctx, String info) {
        showAlert(ctx, info, null);
    }

    public void setGetOrderCallBack(GetOrderCallBack getOrderCallBack) {
        this.getOrderCallBack = getOrderCallBack;
    }

    private static void showAlert(Context ctx, String info, DialogInterface.OnDismissListener onDismiss) {
        new AlertDialog.Builder(ctx)
                .setMessage(info)
                .setPositiveButton(R.string.confirm, null)
                .setOnDismissListener(onDismiss)
                .show();
    }

    private void refresh() {
        // 重新获取order列表
        getOrderCallBack.refreshOrder();

        // 刷新当前页面
        initEvent();
    }
}